<template>
	<view class="container-main" :style="{
		     '--top-bar-height':mp.topBarHeight + 'px',
	         '--safe-area-bottom':mp.systemInfo.safeAreaInsets.bottom + 'px'}" v-if="loading">
		<view class="container-main-top"></view>
		<!-- #ifdef MP-WEIXIN -->
		<go-back>金币充值</go-back>
		<!-- #endif -->
		<view class="main">
			<view class="balance">账户余额：<text class="num">{{wallet.accountBalance}}</text>金币</view>
			<top-up-list :list="wallet.goodsList" @pay="pay"></top-up-list>
			<view class="instructions">
				<view class="biaoti">充值说明</view>
				<view class="content">
					<view>1. 虚拟商品不退换。</view>
					<view>2. 金币套餐是巨上头剧场短剧平台为用户提供的一种充值方式，通过购买金币套餐可以在平台上享受更多的服务和特权。</view>
					<view>3. 金币套餐的价格和内容会在平台上进行公示，用户可以根据自己的需求选择适合的套餐。</view>
					<view>4. 购买金币套餐后，金币特直接充值到您的账户中，可以用于解锁付费内容等。</view>
					<view>5. 金币套餐仅限个人使用，禁止转让、出售或以其他形式进行非法交易。一经发现，平台特采取相应的处理措施。</view>
					<view>6. 未满18周岁的未成年人，应在父母或其他监护人的监护、指导、同意下进行付费等相关操作。</view>
					<view>7. 如有任何问题或疑问，您可以随时联系我们的客服团队，我们将尽快为您解答和处理。</view>
					<view>我们秉承为用户提供高质量、安全可靠的服务的宗旨，希望您在巨上头剧场短剧平台上享受到愉快的使用体验。感谢您的支持与理解！</view>
				</view>
			</view>
		</view>
		<uv-popup ref="popup" mode="bottom" bgColor="none" overlayOpacity="0.8" zIndex="99999" :safeAreaInsetBottom="false">
			<view class="ios-pop">
				<view class="dy-iconfont icon-yuyinguanbi" @tap.stop.prevent="tapDetention"></view>
				<image class="iosNo" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/peng-jc/iosNo.png" mode=""></image>
				<text class="title">由于相关规范，ios功能暂不可用</text>
			</view>
		</uv-popup>
		<!-- #ifdef MP-TOUTIAO -->
		<button class="menu-item-btn" data-im-id="miliner." open-type="im"></button>
		<!-- #endif -->
	</view>
</template>



<script>
	const app = getApp();
	import mp from "@/mixins/mp.js";
	import goBack from '@/components/back/back.vue';
	import topUpList from '@/components/top-up-list/top-up-list.vue';
	import { getUsable, log, payState, myDetail, payStatett } from '@/common/api';
	export default {
		mixins: [mp],
		components: {
			goBack,
			topUpList
		},
		data() {
			return {
				wallet: null,
				loading: false,
				codeTimer: null, //定时器
				codeTime: 14, // 限制1分钟后没请求到erp数据，不再继续请求
			}
		},
		onLoad(option) {
			this.getPageData();
		},
		onShow() {},
		onHide() {},
		onPullDownRefresh: function() {
			this.getPageData();
		},
		watch: {},

		methods: {
			// 加载页面数据
			getPageData: function(callback) {
				uni.showLoading({ title: '正在加载', mask: true });
				Promise.all([this.requestUsable()]).then(() => {
					callback && callback()
				}).catch(() => {
					callback && callback()
				}).finally(() => {
					this.loading = true
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			requestUsable() {
				return new Promise((resolve, reject) => {
					getUsable().then((result) => {
						this.wallet = result
						this.wallet.goodsList = this.wallet.goodsList.filter((item, index) => {
							return item.rechargeType != 2
						})
						resolve();
					}).catch((err) => {
						reject();
					});
				});
			},
			// 支付成功回调
			async pay(e) {
				let that = this
				that.codeTime = 14
				switch (e.payform) {
					case 'tt':
						console.log('pay成功', e);
						if (e.platform != 'ios') this.ttAndroidPay(e)
						else this.ttIosPay(e)
						break;
					case 'wx':
						const { pullPayState } = await myDetail();
						e = Object.assign({ pullPayState: pullPayState }, e)
						if (e.platform != 'ios') this.wxAndroidPay(e)
						// else this.wxIosPay(e)
						
						else this.ttIosPay(e)
						break;
				}
			},
			// 抖音安卓支付
			ttAndroidPay(params) {
				let that = this
				tt.requestOrder({
					data: params.data, // 请勿在前端对data做任何处理
					byteAuthorization: params.byteAuthorization, // 请勿在前端对byteAuthorization做任何处理
					success: (res) => {
						console.log('requestOrder成功', res);
						tt.getOrderPayment({
							orderId: res.orderId,
							success: (r) => {
								console.log('getOrderPayment成功', r);
								that.codeCount(Object.assign({ outOrderNo: r.orderId }, params))
							},
							fail: (res) => {
								console.log(res)
							},
						});

					},
					fail: (res) => {
						console.log(res)
					},
				});
			},
			// 抖音ios支付
			ttIosPay(params) {
				let that = this
				that.$refs.popup.open();
			},
			// 微信安卓支付
			wxAndroidPay(params) {
				let that = this
				wx.requestVirtualPayment({
					signData: params.signData,
					paySig: params.paySig,
					signature: params.signature,
					mode: params.mode,
					success(res) {
						that.codeCount(params)
					},
					fail({ errMsg, errCode }) {
						if (errCode == -2) {} else {
							uni.showModal({
								title: "友情提示",
								content: '系统错误，充值失败',
								showCancel: false
							});
						}
					}
				})
			},
			// 微信ios支付
			wxIosPay(params) {
				let that = this
				if (params.pullPayState == 0) {
					that.$refs.popup.open();
				} else {
					wx.requestPayment({
						timeStamp: params.timeStamp,
						nonceStr: params.nonceStr,
						package: params.package,
						signType: params.signType,
						paySign: params.paySign,
						success(res) {
							that.codeCount(params)
						},
						fail({ errMsg, errCode }) {
							if (errMsg == 'requestPayment:fail cancel') {} else {
								uni.showModal({
									title: "友情提示",
									content: '系统错误，充值失败',
									showCancel: false
								});
							}
						}
					})
				}
			},

			codeCount(params) {
				// #ifdef MP-WEIXIN
				uni.showLoading({ title: '正在查询支付状态', mask: true });
				// #endif
				setTimeout(() => {
					this.codeTimer = setInterval(this.setIntervalFun(params), 3000);
				}, 1000);
			},
			setIntervalFun(params) {
				return () => {
					if (this.codeTime <= 0) {
						uni.hideLoading();
						// #ifdef MP-WEIXIN
						uni.showToast({
							title: '状态查询失败',
							icon: 'error',
							duration: 2000
						});
						// #endif
						this._clearCount()
					} else {
						/*未请求到接口，继续请求数据*/
						this.goPayState(params)
						this.codeTime--;
					}
				}
			},
			goPayState(params) {
				// #ifdef MP-WEIXIN
				payState(params.orderId).then((result) => {
					if (result.payState == 1) {
						uni.hideLoading();
						this._clearCount()
						uni.showToast({
							title: '支付成功-',
							icon: 'success',
							duration: 2000
						});
						this.requestUsable()
					}
				}).catch((err) => {
					uni.hideLoading();
					uni.showToast({
						title: '支付失败',
						icon: 'success',
						duration: 2000
					});
					this._clearCount()
				})
				// #endif

				// #ifdef MP-TOUTIAO
				payStatett({
					outOrderNo: params.orderId,
					orderId: params.outOrderNo
				}).then((result) => {
					if (result.payState == 1) {
						uni.hideLoading();
						this._clearCount()
						this.requestUsable()
					}
				}).catch((err) => {
					uni.hideLoading();
					this._clearCount()
				})
				// #endif
			},
			//清除定时器
			_clearCount() {
				this.codeTimer && clearInterval(this.codeTimer);
				this.codeTimer = null;
				this.codeTime = 0;
			},
			tapDetention() {
				this.$refs.popup.close();
			}
		}
	}
</script>


<style lang="scss">
	page {
		/* #ifdef MP-WEIXIN */
		background: #000;
		/* #endif */
		background: #000;
		// background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/peng-jc/new_bg.png');
		// background-repeat: no-repeat;
		// background-size: 100% 1071rpx;
		// background-position: 0 0;
	}

	.container-main {
		box-sizing: border-box;
		padding: 0 24rpx;
		padding-top: calc(var(--top-bar-height) + 30rpx);
		padding-bottom: calc(var(--safe-area-bottom) + 24rpx);

		.container-main-top {
			position: fixed;
			top: 0;
			left: 0;
			z-index: 99;
			width: 100%;
			height: calc(var(--top-bar-height) + 30rpx);
			background: #000;
			// background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/peng-jc/new_bg.png');
			// background-repeat: no-repeat;
			// background-size: 100% 1071rpx;
			// background-position: 0 0;
		}

		.main {
			.balance {
				font-weight: 400;
				font-size: 26rpx;
				color: #FFFFFF;
				line-height: 37rpx;
				margin-bottom: 47rpx;

				.num {
					font-weight: 400;
					font-size: 36rpx;
					color: #FF6F00;
					line-height: 37rpx;
				}
			}

			.instructions {
				margin-top: 40rpx;

				.biaoti {
					font-weight: 600;
					font-size: 32rpx;
					color: #FFFFFF;
					line-height: 45rpx;
					margin-bottom: 20rpx;
				}

				.content {
					font-weight: 400;
					font-size: 26rpx;
					color: rgba(255, 255, 255, 0.8);
					line-height: 37rpx;
				}
			}
		}

		.ios-pop {
			width: 100vw;
			height: 591rpx;
			background: rgba(255, 255, 255, 1);
			border-radius: 40rpx 40rpx 0rpx 0rpx;
			backdrop-filter: blur(10px);
			position: relative;
			box-sizing: border-box;
			padding-top: 78rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.dy-iconfont {
				position: absolute;
				font-size: 28rpx;
				top: 41rpx;
				right: 43rpx;
			}

			.iosNo {
				width: 260rpx;
				height: 260rpx;
				margin-bottom: 57rpx;
			}

			.title {
				font-weight: 400;
				font-size: 28rpx;
				color: #000;
				line-height: 40rpx;
				text-align: center;
			}
		}
	}

	.menu-item-btn {
		position: fixed;
		right: 0;
		bottom: 600rpx;
		padding: 0;
		margin: 0;
		width: 124rpx;
		height: 129rpx;
		background-image: url('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/peng-jc/service-pp.png');
		background-color: transparent;
		background-repeat: no-repeat;
		background-size: cover;
	}
</style>